<template>
  <div>
    <!-- 页面头部 -->
    <header>
      <div class="logo">
        <h1>Raccoon Guide</h1>
      </div>
      <div class="header-links">
        <button @click="goToHall" class="hall-button">Go to Hall</button>
      </div>
    </header>

    <!-- 内容区域 -->
    <main>
      <h2>Starred Links</h2>
      <div id="starred-link-list-container">
        <table v-if="starredLinks.length > 0" class="starred-links-table">
          <thead>
            <tr>
              <th>Link Name</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="link in starredLinks" :key="link.id">
              <td>{{ link.name }}</td>
              <td>
                <button @click="removeStar(link.id)">Remove Star</button>
              </td>
            </tr>
          </tbody>
        </table>
        <div v-else>No starred links found.</div>
      </div>
    </main>
  </div>
</template>

<script lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'StarPage',
  setup() {
    const router = useRouter();
    const starredLinks = ref<any[]>([]); // 存储已点过赞的链接
    const userId = ref(localStorage.getItem("userId"));
    console.log(userId)

    // 获取已点过赞的链接数据
    const fetchStarredLinks = async (userId: string) => {
      try {
        const response = await fetch(`http://localhost:7777/getUserLikedLinks?userId=${userId}`);
        if (!response.ok) throw new Error(`Failed to fetch starred links. Status: ${response.status}`);

        const data = await response.json();
        starredLinks.value = data.data || [];
      } catch (error) {
        console.error("Error fetching starred links:", error);
        starredLinks.value = [];
      }
    };

    // 组件挂载时，检查用户是否登录，并获取已点过赞的链接
    onMounted(async () => {
      if (!userId.value) {
        alert("Please log in first.");
        router.push("/login");
      } else {
        await fetchStarredLinks(userId.value);
      }
    });

    // 处理返回大厅按钮点击
    const goToHall = () => {
      router.push("/");
    };

    // 移除点赞
    const removeStar = async (linkId: string) => {
      if (!userId.value) {
        alert("Please log in to remove star.");
        return;
      }

      try {
        const response = await fetch(`http://localhost:7777/removeStar`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ userId: userId.value, link_id: linkId })
        });

        const data = await response.json();
        if (data.message === 'Star removed successfully') {
          starredLinks.value = starredLinks.value.filter(link => link.id !== linkId);
          alert('Star removed successfully.');
          await fetchStarredLinks(userId.value);
        } else {
          alert('Failed to remove star.');
        }
      } catch (error) {
        console.error('Error removing star:', error);
        alert('An error occurred. Please try again.');
      }
    };

    return {
      starredLinks,
      goToHall,
      removeStar
    };
  }
};
</script>

<style scoped>
/* 基本样式 */
body {
  background-color: #f0f0f0;
}

header {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #f8f8f8;
  border-bottom: 2px solid #ccc;
}

header .logo h1 {
  margin: 0;
}

header .header-links button {
  margin-left: 15px;
}

main {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
}

#starred-link-list-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.starred-links-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
  border-radius: 5px;
}

.starred-links-table th,
.starred-links-table td {
  padding: 10px;
  border: 1px solid #ddd;
  text-align: left;
}

.starred-links-table th {
  background-color: #f4f4f4;
}

button {
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
